﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Permission.Interfaces;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Permission.Models;
using Microhard.Core.Algorithm;
using Microhard.Core.DBUtility;
using Microhard.Framework.MVCHelper;

namespace Microhard.Permission.MVCFilter
{
    public class MVCFilterAtrForCustomeDataPermission : ActionFilterAttribute, IMvcFilter
    {
        private Type _validator;
        private IUser user = IoC.Resolve<IUser>();
        private IDataCollectionAuthorization ica = IoC.Resolve<IDataCollectionAuthorization>();
        private IDataPermission id = IoC.Resolve<IDataPermission>();
        private string _dataScopeactionParameterName = "scope";

        public MVCFilterAtrForCustomeDataPermission()
        {
            //表示作为action filter第4个执行
            this.Order = 3;
        }

        public string DataScopeactionParameterName
        {
            set
            {
                this._dataScopeactionParameterName = value;
            }
            get
            {
                return this._dataScopeactionParameterName;
            }
        }

        public MVCFilterAtrForCustomeDataPermission(Type validator)
        {
            _validator = validator;
        }

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            string msg = "您对此数据没有访问权限，请向管理员申请";
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = msg,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "NeedDataPermission";
                filterContext.Result = ad;
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User currentUser = MVCFilterAtrForLogon.GetLogonUser();
            List<Guid> identities = new List<Guid>();
            if (filterContext.ActionParameters.Keys.Contains("identity"))
            {
                identities.Add((Guid)filterContext.ActionParameters["identity"]);
            }
            else if (filterContext.ActionParameters.Keys.Contains("identities"))
            {
                identities = (List<Guid>)filterContext.ActionParameters["identities"];
            }
            else
            {
                if (filterContext.ActionParameters.Keys.Contains("model"))
                {
                    var model = filterContext.ActionParameters["model"];
                    identities.Add(AlgCompare.GetPKID<ModelPKIDAttribute>(model));
                }
            }
            var currentPermissions = filterContext.HttpContext.Items[SysConst.DATACOLLECTION_PERMISSIONID] as List<Microhard.Permission.Models.Permission>;
            if (currentPermissions == null)
            {
                this.RedirectToPage(filterContext);
                return;
            }
            var dataScope = ica.GetDataScope(currentPermissions.First().ResID, currentUser);
            //从之前的scope 中取出，并将员工信息赋予到现在的scope中
            if (filterContext.ActionParameters.Keys.Contains(this._dataScopeactionParameterName))
            {
                var scope = filterContext.ActionParameters[this._dataScopeactionParameterName] as ScopeResult;
                if (scope != null)
                {
                    dataScope.CurrentUserRealName = scope.CurrentUserRealName;
                    dataScope.CurrentUserRoleNames = scope.CurrentUserRoleNames;
                    dataScope.EmpInfo = scope.EmpInfo;
                }
            }
            filterContext.ActionParameters[this._dataScopeactionParameterName] = dataScope;
            ICustomeDataPermissionValidator validator = null;
            if (_validator != null)
            {
                validator = IoC.Resolve(_validator) as ICustomeDataPermissionValidator;
                validator.scope = dataScope;
            }

            if (identities != null && identities.Count > 0)
            {
                if (!validator.HasPermission(identities))
                {
                    this.RedirectToPage(filterContext);
                    return;
                }
            }

        }


    }
}
